import { Author } from '@/entities/Author';
import { initORM } from '@/utils/back';
import { NextApiResponse } from 'next';
import { NextRequest } from 'next/server';

export async function getAuthor(req: NextRequest) {
  const authorId = req.nextUrl.searchParams.get('authorId');
  const em = await initORM();
  const user = await em.findOne(Author, Number(authorId));

  return user;
}

export async function updateAuthor(
  req: NextRequest,
  res: NextApiResponse<APIRes>
) {
  const body = (await req.json()) || (await req.formData());
  const { email, name, id } = body ?? {};
  if (!id) {
    res.status(400).json({
      success: false,
      data: {},
      message: 'Missing author id',
    });
    return;
  }

  const searchParams = req.nextUrl.searchParams;
  searchParams.set('authorId', id);
  const targetAuthor = await getAuthor(req);
  if (!targetAuthor) {
    res.status(400).json({
      success: false,
      data: {},
      message: 'Author not found',
    });
    return;
  }

  const message = 'update success';
  targetAuthor.email = email;
  targetAuthor.name = name;

  const em = await initORM();
  await em.persistAndFlush(targetAuthor);

  res.status(200).json({
    success: true,
    data: {},
    message,
  });
}

export async function getAuthors(req: NextRequest) {
  // const em = await initORM();
  // const authors = await em.findAll(Author, {});

  // return authors;
  return [];
}

export async function createUser(
  req: NextRequest,
  res: NextApiResponse<APIRes>
) {
  const em = await initORM();
  const body = (await req.json()) || (await req.formData());
  const author = await em.create(Author, body);
  await em.persistAndFlush(author);

  res.status(200).json({ success: true, data: {}, message: 'author created' });
}
